<?php

namespace App\Http\Controllers;

use App\Models\ProposalDefense;
use App\Models\ProposalReport;
use Illuminate\Http\Request;

class ProposalDefenseController extends Controller
{
    public function index()
    {
        $defenses = ProposalDefense::with(['proposalReport.topicSelection.student.user', 'proposalReport.topicSelection.thesisTopic.teacher.user'])->get();
        return response()->json($defenses);
    }

    public function store(Request $request)
    {
        $request->validate([
            'proposal_id' => 'required|exists:proposal_reports,id',
            'record' => 'required|string',
            'score' => 'nullable|numeric|min:0|max:100',
            'feedback' => 'nullable|string',
        ]);

        $proposal = ProposalReport::findOrFail($request->proposal_id);
        if ($proposal->status !== 'approved') {
            return response()->json(['message' => 'Proposal report must be approved first'], 422);
        }

        $defense = ProposalDefense::create($request->all());
        return response()->json($defense->load(['proposalReport.topicSelection.student.user', 'proposalReport.topicSelection.thesisTopic.teacher.user']), 201);
    }

    public function show(ProposalDefense $defense)
    {
        return response()->json($defense->load(['proposalReport.topicSelection.student.user', 'proposalReport.topicSelection.thesisTopic.teacher.user']));
    }

    public function update(Request $request, ProposalDefense $defense)
    {
        $request->validate([
            'record' => 'string',
            'score' => 'nullable|numeric|min:0|max:100',
            'feedback' => 'nullable|string',
        ]);

        $defense->update($request->all());
        return response()->json($defense->load(['proposalReport.topicSelection.student.user', 'proposalReport.topicSelection.thesisTopic.teacher.user']));
    }

    public function destroy(ProposalDefense $defense)
    {
        $defense->delete();
        return response()->json(null, 204);
    }
} 